package com.calm.clibrary.rvadapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

/**
 * 适用于RecyclerView的通用ViewHolder
 * Create by Calm
 * on 2019/4/10
 */
public class CommRvHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private SparseArray<View> viewSparseArray;
    private CommRvOnItemClickListener commRvOnItemClickListener;
    public interface CommRvOnItemClickListener{
        void onItemClickListener(int position);
    }
    public CommRvHolder(View itemView){
        super(itemView);
        itemView.setOnClickListener(this);
        viewSparseArray = new SparseArray<>();
    }

    /**
     * 根据view Id来获取View
     * @param viewId Id
     * @param <T> View
     * @return T
     */
    public <T extends View> T getViw(int viewId){
        View view = viewSparseArray.get(viewId);
        if(view == null){
            view = itemView.findViewById(viewId);
            viewSparseArray.put(viewId,view);
        }
        return (T)view;
    }
    public CommRvHolder setCommRvOnItemClickListener(CommRvOnItemClickListener listener){
        this.commRvOnItemClickListener = listener;
        return this;
    }
    @Override
    public void onClick(View v) {
        if(commRvOnItemClickListener != null){
            commRvOnItemClickListener.onItemClickListener(getAdapterPosition());
        }
    }
}
